package com.blue.base.security.filters;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blue.base.common.constants.UserConstants;
import com.blue.base.common.jwt.JwtConfig;
import com.blue.base.redis.utils.RedisUtils;
import com.blue.base.security.api.AuthService;
import com.blue.base.security.config.SecurityAuthConfig;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * jwt-token 过滤器
 *
 * @author liulei
 * @version 1.0
 */
@Slf4j
@AllArgsConstructor
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {

    private AuthService authService;
    private SecurityAuthConfig authConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 过滤不必要做token校验的url
        if (ifSkipTokenCheck(request, authConfig)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 根据token获取登录用户信息
        String token = request.getHeader(JwtConfig.AUTH_TOKEN);
        String account = authService.getAccountByToken(token);
        UserDetails userDetails;
        if (null != RedisUtils.get(UserConstants.getUserRedisKey(account))) {
            userDetails = authService.loadUserByUsername(account);
        } else {
            String userRedisKey = UserConstants.getUserRedisKey(account);
            JSONObject jsonObject = JSON.parseObject(RedisUtils.get(userRedisKey));
            userDetails = JSON.toJavaObject(jsonObject, UserDetails.class);
            RedisUtils.set(userRedisKey, jsonObject.toJSONString(), JwtConfig.EXPIRE);
        }
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }

    /**
     * 过滤不必要校验的url及文件路径
     *
     * @param request    请求
     * @param authConfig 鉴权配置
     */
    private boolean ifSkipTokenCheck(HttpServletRequest request, SecurityAuthConfig authConfig) {
        String servletPath = request.getServletPath();
        List<String> skipUrl = authConfig.getSkipUrl();
        skipUrl.add(authConfig.getLoginUrl());
        skipUrl.add(authConfig.getLogoutUrl());
        skipUrl.stream().anyMatch(s -> new AntPathMatcher().match(s, servletPath));
        return skipUrl.contains(servletPath);
    }
}
